<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ReviewForm;
use App\Admin\Controllers\Helpers\LinkHelper;
use App\Constant\Enum;
use App\Models\Transaction;
use App\Models\UserWithdraw;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Show;
use App\Models\User;
use App\Admin\Renderable\AdrewardDetailsTable;

class UserWithdrawController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new UserWithdraw(), function (Grid $grid) {
            $grid->model()->where('wallet_type', '!=', Enum::WALLET_TYPE_COMMISSION);
            $grid->model()->with(['user', 'transaction', 'operator', 'parent', 'member']);
            $grid->quickSearch('id', 'user_id', 'user.uuid', 'user.nickname')->placeholder('输入 id\uuid\用户昵称\uid')->auto(false);;
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->select('user.status', '用户状态', Enum::getStatusExplains());
                $selector->select('user.is_group_leader', '是否团长', [
                    1 => '是', 0 => '否'
                ]);
                $selector->select('status', '审核状态', [
                    Enum::WITHDRAW_STATUS_PENDING => '待审核',
                    Enum::WITHDRAW_STATUS_REJECTED => '已拒绝',
                    Enum::WALLET_ACTIVE_STATUS_APPROVED => '已通过',
                ]);
            });
            $grid->model()->orderBy('applied_at', 'desc');

            $grid->column('id')->sortable();

            $grid->column('user_id')->display(function () {
                return LinkHelper::displayUsernotlink($this->user);
            })->modal('红包明细', function () {

                // 通过模型获取 user_id

                return AdrewardDetailsTable::make()->payload(['user_id' => $this->user_id]);

            });

            $grid->column('money')->display(function () {
                $money = $this->money;
                $url = admin_url("user-adreward-details?user_id={$this->user->id}");
                return "<a href='javascript:void(0);' class='open-user-withdraw' data-url='{$url}' style='color:#409EFF;'>$money</a>";
            });
            $grid->column('user.parent_id', '来源(上级)')
                ->width('200')
                ->display(function () {


                    $parent = User::query()->find($this->user->parent_id);
                    $leader = $this->member->leader ?? '';

                    $text = '<i>-</i>';
                    if ($parent) {
                        $text = "师傅: <a href='?id={$parent->id}'>{$parent->nickname}｜<b>{$parent->uuid}</b></a>";
                    }
                    if ($leader) {
                        $text .= "<br/> 团长: <a href='?id={$leader->id}'>{$leader->nickname}｜<b>{$leader->uuid}</a>";
                    }
                    return "<div style='font-size: smaller'>{$text}</div>";
                });
            $grid->column('user.is_group_leader', '普通团长')
                ->using([
                    1 => '是',
                    0 => '否'
                ])
                ->label([
                    1 => 'success',
                    0 => 'default',
                ]);
            $grid->column('user.is_advanced_group', '高级团长')
                ->using([
                    1 => '是',
                    0 => '否'
                ])
                ->label([
                    1 => 'success',
                    0 => 'default',
                ]);
            // $grid->column('wid');
            //   $grid->column('wallet_type');
            $grid->column('exchange_rate');
            $grid->column('amount');
            $grid->column('status')->using([
                Enum::WITHDRAW_STATUS_PENDING => '待审核',
                Enum::WITHDRAW_STATUS_REJECTED => '已拒绝',
                Enum::WALLET_ACTIVE_STATUS_APPROVED => '已通过',
            ], '未知')->label([
                Enum::WITHDRAW_STATUS_PENDING => 'info',
                Enum::WITHDRAW_STATUS_REJECTED => 'danger',
                Enum::WALLET_ACTIVE_STATUS_APPROVED => 'success',
            ]);

            $grid->column('transaction_status', '转账状态')->display(function () {
                /** @var Transaction $transaction */
                $transaction = $this->transaction;
                if ($transaction) {
                    return $transaction['status'];
                }
                return $this->id;
            })->using([
                Enum::TRANSACTION_STATUS_PENDING => '已发起',
                Enum::TRANSACTION_STATUS_REJECT => '失败',
                Enum::TRANSACTION_STATUS_APPROVED => '成功',
            ], '未知')->label([
                Enum::TRANSACTION_STATUS_PENDING => 'info',
                Enum::TRANSACTION_STATUS_REJECT => 'danger',
                Enum::TRANSACTION_STATUS_APPROVED => 'success',
            ]);

            $grid->column('operator_id', '操作人')->display(function ($adminId) {
                return $this->operator->username ?? '-';
            });
            $grid->column('applied_at')->sortable();
            $grid->column('audited_at')->sortable();
            $grid->column('remark')->limit(10);

            $grid->column('action', ' ')
                ->width('100')
                ->display('审核')
                ->modal(function () {
                    /** @var UserWithdraw $model */
                    $model = $this;

                    return ReviewForm::make([
                        'message' => sprintf('%s[%s], 提现 %s 元', $model->user->nickname, $model->user->uuid, $model->money),
                        'withdraw_id' => $model->getAttribute('id')
                    ]);
                });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->equal('user_id');

                $filter->equal('status')->radio([
                    Enum::WITHDRAW_STATUS_PENDING => '待审核',
                    Enum::WITHDRAW_STATUS_REJECTED => '已拒绝',
                    Enum::WALLET_ACTIVE_STATUS_APPROVED => '已通过',
                ]);
            });

            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableBatchDelete();

            $grid->fixColumns(4, -2);
            Admin::script(<<<JS
            $(document).off('click', '.open-user-withdraw').on('click', '.open-user-withdraw', function () {
                var url = $(this).data('url');
                layer.open({
                type: 2,
                title: '用户收益记录',
                area: ['1200px', '900px'],
                shadeClose: true,
                content: url
        });
            });
        JS
            );
        });

    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new UserWithdraw(), function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('wid');
            $show->field('wallet_type');
            $show->field('money');
            $show->field('exchange_rate');
            $show->field('amount');
            $show->field('status');
            $show->field('operator_id');
            $show->field('applied_at');
            $show->field('audited_at');
            $show->field('remark');
            $show->field('created_at');
            $show->field('updated_at');

            $show->disableEditButton();
            $show->disableDeleteButton();
        });
    }
}
